/* **************************************************
 Copyright (c) 2012, University of Cambridge
 Neal Lathia, neal.lathia@cl.cam.ac.uk
 Kiran Rachuri, kiran.rachuri@cl.cam.ac.uk

This library was developed as part of the EPSRC Ubhave (Ubiquitous and
Social Computing for Positive Behaviour Change) Project. For more
information, please visit http://www.emotionsense.org

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 ************************************************** */

package com.ubhave.sensormanager.sensors.pull;

import java.util.ArrayList;

import com.ubhave.sensormanager.ESException;
import com.ubhave.sensormanager.config.pull.MotionSensorConfig;
import com.ubhave.sensormanager.data.pull.AbstractMotionData;
import com.ubhave.sensormanager.utils.LogUtil;
import ohos.app.Context;
import ohos.sensor.agent.CategoryEnvironmentAgent;
import ohos.sensor.agent.CategoryMotionAgent;
import ohos.sensor.agent.SensorAgent;
import ohos.sensor.bean.CategoryMotion;
import ohos.sensor.bean.SensorBase;
import ohos.sensor.data.CategoryMotionData;
import ohos.sensor.data.SensorData;
import ohos.sensor.listener.ICategoryMotionDataCallback;
import ohos.sensor.listener.ISensorDataCallback;

/**
 * 运动传感器抽象
 */
public abstract class AbstractMotionSensor extends AbstractPullSensor {
    private final int motionSensorType;
    private final ICategoryMotionDataCallback listener; // data listener
    private final CategoryMotionAgent sensorManager; // Controls the hardware sensor

    protected ArrayList<float[]> sensorReadings;
    protected ArrayList<Long> sensorReadingTimestamps;
    protected AbstractMotionData data;

    protected AbstractMotionSensor(final Context context, final int motionSensorType) throws ESException {
        super(context);
        this.motionSensorType = motionSensorType;
        sensorManager = new CategoryMotionAgent();
        if (getSensor() == null) {
            throw new ESException(ESException.SENSOR_UNAVAILABLE, getLogTag() + " is null (e.g., missing from device).");
        } else {
            listener = getListener();
        }
    }

    protected SensorBase getSensor() {
        return sensorManager.getSingleSensor(motionSensorType);
    }

    protected ICategoryMotionDataCallback getListener() {
        return new ICategoryMotionDataCallback() {

            /*
             * This method is called when the sensor takes a reading:
             * despite the name, it is called even if the data is the same as
             * the previous one
             */
            @Override
            public void onSensorDataModified(CategoryMotionData event) {
                try {
                    if (isSensing) {
                        synchronized (sensorReadings) {
                            if (isSensing) {
                                float[] data = new float[event.values.length];
                                for (int i = 0; i < event.values.length; i++) {
                                    data[i] = event.values[i];
                                }
                                sensorReadings.add(data);
                                sensorReadingTimestamps.add(System.currentTimeMillis());
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            /*
             * This method is required by the API and is called when the
             * accuracy of the readings being generated by the sensor changes.
             * We currently don't do anything when this happens.
             */
            @Override
            public void onAccuracyDataModified(CategoryMotion categoryMotion, int i) {

            }

            @Override
            public void onCommandCompleted(CategoryMotion categoryMotion) {

            }
        };
    }

    protected boolean startSensing() {
        sensorReadings = new ArrayList<float[]>();
        sensorReadingTimestamps = new ArrayList<Long>();

        SensorBase sensor = getSensor();
        long minInterval = sensor.getMinInterval();


        boolean registrationSuccess = sensorManager.setSensorDataCallback(listener, sensorManager.getSingleSensor(motionSensorType), minInterval);
        LogUtil.loge("===registrationSuccess: " + registrationSuccess);
        LogUtil.loge("===minInterval: " + minInterval);
        return registrationSuccess;
    }

    protected void stopSensing() {
        sensorManager.releaseSensorDataCallback(listener);
    }

    protected AbstractMotionData getMostRecentRawData() {
        return data;
    }
}
